package com.example.floatingpopulation.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.floatingpopulation.controller.dto.LoginDTO;
import com.example.floatingpopulation.controller.request.BaseRequest;
import com.example.floatingpopulation.controller.request.LoginRequest;
import com.example.floatingpopulation.entity.Admin;
import com.example.floatingpopulation.entity.Password;
import com.example.floatingpopulation.entity.Permissions;
import com.example.floatingpopulation.exception.ServiceException;
import com.example.floatingpopulation.mapper.AdminMapper;
import com.example.floatingpopulation.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Slf4j
@Service
public class AdminServiceImpl implements com.example.floatingpopulation.service.AdminService {
    private static final String DEFAULT_PASS = "admin123";
    private static final String PASS_SALT = "qiu";

    @Autowired
    AdminMapper adminMapper;
    @Override
    public List<Admin> list() {
        return adminMapper.list();
    }

    @Override
    public PageInfo<Admin> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(),baseRequest.getPageSize());
        List<Admin> users = adminMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(Admin obj) {
        Date date = new Date();
        //密码加密
        obj.setPassword(securePass(obj.getPassword()));
        //用户登录的账号
        obj.setAdminId(DateUtil.format(date,"yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        adminMapper.save(obj);
    }

    @Override
    public void update(Admin obj) {
        obj.setUpdateTime(new Date());
        adminMapper.updateById(obj);
    }

    @Override
    public void deleteById(Integer id) {
        adminMapper.deleteById(id);
    }

    @Override
    public LoginDTO login(LoginRequest request) {
        //密码解密
        request.setPassword(securePass(request.getPassword()));
        Admin admin = adminMapper.getByAdminNameAndPassword(request);
        if (admin == null){
            throw new ServiceException("用户名或密码错误");
        }
        LoginDTO loginDTO = new LoginDTO();
        BeanUtils.copyProperties(admin,loginDTO);
        //生成token
        String token = TokenUtils.genToken(String.valueOf(admin.getId()), admin.getPassword());
        loginDTO.setToken(token);
        // 查询权限
        Permissions permissions = adminMapper.getPermissions(loginDTO.getIsAdmin());
        if (permissions != null) {
            List<String> list = Arrays.stream(Permissions.class.getDeclaredFields())
                    .filter(field -> {
                        try {
                            field.setAccessible(true);
                            return "1".equals(field.get(permissions));
                        } catch (IllegalAccessException e) {
                            return false;
                        }
                    })
                    .map(Field::getName)
                    .collect(Collectors.toList());
            // 直接将权限列表赋值给 loginDTO
            loginDTO.setPermissions(list);
        }
        return loginDTO;
    }

    @Override
    public Admin getById(Integer id) {
        return adminMapper.getById(id);
    }

    @Override
    public void resetPassword(Admin admin) {
        // 重置密码为"123456"
        admin.setPassword(DEFAULT_PASS);
        // 设置md5加密 防止解密再加字符
        admin.setPassword(SecureUtil.md5(admin.getPassword() + PASS_SALT));
        adminMapper.resetPassword(admin);
    }

    @Override
    public void updatePassword(Password password){
        // 设置md5加密 防止解密再加字符
        password.setPassword(SecureUtil.md5(password.getConfirmPassword() + PASS_SALT));
        adminMapper.updatePassword(password);
    }


    //加密方法 设置md5加密 防止解密再加字符
    private String securePass(String password){
        return SecureUtil.md5(password + PASS_SALT);
    }

}
